<template>
  <div class="bg-white">
    <Card>
      <SearchForm @get="formParamsHandle"></SearchForm>
    </Card>
    <Card>
      <div style="margin-bottom: 16px">
        <Button type="link" :disabled="!hasSelected" @click="show(selectRecords)"> 查看多行详情</Button>
      </div>
      <Table
        class="main-table"
        sticky
        :bordered="true"
        :dataSource="dataSource"
        :columns="columns"
        :row-selection="{
          selectedRowKeys: state.selectedRowKeys,
          onChange: onSelectChange,
          onSelect: onSelect,
          onSelectAll: onSelectAll,
        }"
        :rowKey="
          (record) => {
            return record.cceResourceId;
          }
        "
        :pagination="false"
        :loading="loading"
        :scroll="scroll"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'action'">
            <span v-per="'detail'">
              <a @click="show(record)">查看详情</a>
            </span>
          </template>
        </template>
      </Table>
      <br />
      <Pagination
        show-size-changer
        v-model:current="current"
        v-model:pageSize="pageSize"
        :total="total"
        :show-total="(total) => `共 ${total} 条`"
        @showSizeChange="onShowSizeChange"
      />
    </Card>
    <Detail ref="detailSwitch" :chartList="chartList" :detailParams="detailParams" @close="close" />
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref, toRefs, watch } from 'vue';
import { Card, Table, Button, Pagination } from 'ant-design-vue';
import SearchForm from '/@/views/measurement-center/source-statistic/component/searchForm.vue';
import Detail from '/@/views/measurement-center/source-statistic/component/detail.vue';
import { getDetailList, getSourceStatisticList } from '/@/api/measurement-center/source-statistic/sourceStatistic';
import { detailItems, sourceItem } from '/@/api/measurement-center/source-statistic/model/sourceStatisticModel';
import { ColumnProps } from 'ant-design-vue/lib/table/interface';

const loading = ref(true);
const scroll = ref<undefined | object>(undefined);
let dataSource = ref();

const detailSwitch = ref();
let chartList = ref<detailItems[]>([]);
let selectRecords = ref([] as any[]);
let hasSelected = ref<boolean>(false);
type Key = ColumnProps['key'];
const state = reactive<{
  selectedRowKeys: Key[];
}>({
  selectedRowKeys: [],
});
const onSelectChange = (selectedRowKeys: Key[]) => {
  state.selectedRowKeys = selectedRowKeys;
};
let current = ref(1);
const total = ref<number>(0);
const pageSize = ref(10);
let params = {
  tenantCodeList: undefined,
  componentIdList: undefined,
  startDate: '',
  endDate: '',
  size: pageSize.value,
  current: current.value,
};

const getDataSource = async () => {
  try {
    let data = await getSourceStatisticList(params);

    dataSource.value = data.items;

    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

const onShowSizeChange = (current: number, pageSize: number) => {
  params.size = pageSize;
  params.current = current;
  getDataSource();
};
watch(pageSize, (val) => {
  if (val > 10) {
    scroll.value = { y: 500 };
  }
  params.size = pageSize.value;
});
watch(current, () => {
  params.current = current.value;
  getDataSource();
});

let detailParams = ref({
  cceResourceIdList: [] as any[],
  period: 'day',
  statistic: 'max',
  startDate: '',
  endDate: '',
});

const columns = [
  {
    title: '租户名称',
    dataIndex: 'tenantName',
    key: 'tenantName',
    width: '200px',
  },
  {
    title: '工作负载',
    dataIndex: 'currentDeployment',
    key: 'currentDeployment',
    width: '200px',
  },
  {
    title: '应用名称',
    dataIndex: 'appName',
    key: 'appName',
    width: '200px',
  },
  {
    title: '组件名称',
    dataIndex: 'componentName',
    key: 'componentName',
    width: '200px',
  },
  {
    title: '是否共享',
    dataIndex: 'isShared',
    key: 'isShared',
    width: '200px',
  },

  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: '200px',
  },
];

const onSelect = (record: sourceItem, selected: boolean, selectedRows: sourceItem[]) => {
  if (selectedRows.length > 1) {
    hasSelected.value = true;
  } else {
    hasSelected.value = false;
  }
  selectRecords.value = selectedRows;
};

const onSelectAll = (selected: boolean, selectedRows: sourceItem[]) => {
  if (selectedRows.length > 1) {
    hasSelected.value = true;
  } else {
    hasSelected.value = false;
  }
  selectRecords.value = selectedRows;
};

const handleParams = (handleParams) => {
  let ts0;
  let ts1;
  let params;
  if (handleParams.date) {
    ts0 = new Date(handleParams.date[0].format('YYYY-MM-DD'));
    ts1 = new Date(handleParams.date[1].format('YYYY-MM-DD'));
  } else {
    ts0 = handleParams.startDate;
    ts1 = handleParams.endDate;
  }

  params = {
    tenantCodeList: handleParams.tenantCodeList,
    componentIdList: handleParams.componentIdList,
    startDate: ts0,
    endDate: ts1,
    size: 10,
    current: 1,
  };
  detailParams.value.startDate = ts0;
  detailParams.value.endDate = ts1;
  return params;
};

const { selectedRowKeys } = toRefs(state);

const formParamsHandle = async (formParams) => {
  if (formParams.selectedRowKeys && formParams.selectedRowKeys.length == 0) {
    hasSelected.value = false;
    selectedRowKeys.value = formParams.selectedRowKeys;
  }
  params = handleParams(formParams);
  let result = await getSourceStatisticList(params);
  dataSource.value = result.items;
  total.value = result.total;
  let cce;
  detailParams.value.cceResourceIdList = [];
  for (let i = 0; i < dataSource.value.length; i++) {
    cce = dataSource.value[i].cceResourceId;
    detailParams.value.cceResourceIdList.push(cce);
  }
};

const show = async (record) => {
  detailSwitch.value.openDetail();
  let cce;

  detailParams.value.cceResourceIdList = [];
  detailParams.value.startDate = params.startDate;
  detailParams.value.endDate = params.endDate;

  if (record.length === undefined) {
    detailParams.value.cceResourceIdList.push(record.cceResourceId);
  } else {
    for (let i = 0; i < record.length; i++) {
      cce = record[i].cceResourceId;
      detailParams.value.cceResourceIdList.push(cce);
    }
  }

  chartList.value = await getDetailList(detailParams.value);
  for (let i = 0; i < detailParams.value.cceResourceIdList.length; i++) {
    chartList.value[i].metricName = detailParams.value.cceResourceIdList[i];
  }
};

const close = () => {
  detailSwitch.value.closeDetail();
};

onMounted(async () => {
  params.startDate = new Date(new Date().getTime() + 8 * 60 * 60 * 1000 - 7 * 24 * 60 * 60 * 1000)
    .toJSON()
    .split('T')
    .join(' ')
    .substr(0, 19)
    .split(' ')[0];
  params.endDate = new Date(new Date().getTime() + 8 * 60 * 60 * 1000)
    .toJSON()
    .split('T')
    .join(' ')
    .substr(0, 19)
    .split(' ')[0];
  getDataSource();
});
</script>
<style lang="less">
.ant-pagination {
  float: right;
}
</style>
